<?php
require_once("../include/connect.php");
class user {
	protected $config=array( 
		'pages'=>array( // Kullanacağımız sayfanın linkleri
		  'login'=>'pera/admin/login.php',
		  'loginkontrol'=>'pera/admin/login.php?step=2'
	  ),
		'password'=>array(
			'min'=>6, // minumum password length allowed
			'salt'=>'a bunch of random characters and symbols for security' // random characters for salting passwords & sessions
		),
		'site'=>array(
			'admin'=>'Zafer OBA', // your name
			'email'=>'zafer@roa.com.rt', // address to send new account emails from
			'name'=>'Pera Kültür', // site name to display in emails
			'cookie'=>'prakltr' // cookie name mktgdept
 		)
	);	
	
	public function require_login(){ //login kontrolü
		if(!$this->logged_in()){
			$_SESSION['redirect']=$_SERVER['REQUEST_URI'];
			$this->fail('Lütfen giriiş yapınız','/'.$this->config['pages']['login']);
		}
	}
	
	public function logged_in(){ // Loginse true dönen fonksiyon
		return ($this->valid_session()&&isset($_SESSION['user']['id'])&&isset($_SESSION['user']['name'])&&isset($_SESSION['user']['email']));
	}
	
	private function valid_session(){ // returns true if the session is valid
		return ($_SESSION['thumbprint']==$this->nonce(session_id().'thumbprint',86400));
	}
	
	protected function nonce($str='',$expires=300){ // generates a secure nonce
		return md5(date('Y-m-d H:i',ceil(time()/$expires)*$expires).$_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].$this->config['password']['salt'].$str);
	}

	function admin_login_form(){ // prints the login form
	echo "".
		 '<div id="login" class="content">'."\n".
		   '<div class="roundedBorders login-box">'."\n".
		     '<div id="title" class="b2">'."\n".
		       '<h2>Pera Kültür Giriş</h2>'."\n".
		     '</div>'."\n".
		   '<div id="innerContent">'."\n".
		     '<form method="post" action="/'.$this->config['pages']['login'].'">'."\n".
               '<div class="field">'."\n".
		         '<label for="username">E-mail</label>'."\n".
                 '<input type="text" class="text" id="email" name="email" value=""/>'."\n".
		       '</div>'."\n".
		       '<div class="field">'."\n".
			     '<label for="password">Şifre</label>'."\n".
			     '<input type="password" class="text" id="password" name="password" value=""/>'."\n".
		       '</div>'."\n".
		       '<div id="error">'."\n".
		         '<p class="error">'.$this->errors().'</p>'."\n".
		       '</div>'."\n".
		       '<div class="clearfix login-submit">'."\n".
		         '<span class="fright">'."\n".
			       '<button class="button" type="submit"><strong>Giriş</strong></button>'."\n".
			     '</span>'."\n".
		       '</div>'."\n".
		     '</form>'."\n".
		   '</div>'."\n".
		   '<div class="bBottom"><div></div></div>'."\n".
		 '</div>'."\n".
	   '</div>'."\n";
	}
	
	function admin_login(){ // processes the login form
      if(!isset($_POST['email'])||!isset($_POST['password']))
			die();
		$email=strtolower($_POST['email']);
		$password=$_POST['password'];
		if(!$this->is_mail($email))
			$this->fail("Hatalı bir mail adresi girdiniz. Lütfen kontrol ediniz..."); // invalid character in username or sql injection attempt
		$password=md5(sha1($email).$this->config['password']['salt'].sha1($password));
		
		$sql="SELECT * FROM users WHERE username='$urlun' and password='$cleanpw'";
        $result=mysql_query($sql);
        $count=mysql_num_rows($result);
		/*
		$q=$db->prepare("SELECT id, name, email, temp FROM users WHERE name=? AND password=?");
		$q->execute(array($name,$password));
		$result=$q->fetch(PDO::FETCH_ASSOC);
		*/
		if(!$result)
			$this->fail("Invalid username or password"); // invalid username or password
		else
			if($result['temp'][0]=='a')
				$this->fail("You have not activated your account"); // account not activated
		session_regenerate_id();
		$_SESSION['thumbprint']=$this->nonce(session_id().'thumbprint',86400);
		$_SESSION['user']['id']=$result['id'];
		$_SESSION['user']['name']=$result['name'];
		$_SESSION['user']['email']=$result['email'];
		$redirect=(isset($_SESSION['redirect'])?$_SESSION['redirect']:'/');
		unset($_SESSION['redirect']);
		$this->do_action('login',array($result['id'],$result['name'],$result['email']));
		header('Location: '.$redirect);
		die();
	}
	
	function logout(){
		//$this->do_action('logout',array($_SESSION['user']['id'],$_SESSION['user']['name'],$_SESSION['user']['email']));
		session_unset();
		session_destroy();
		header('Location: /');
		die();
	}
	
	
	public function is_email($str){ // E-mail kontrolü
	 return ereg("^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+([a-z]{2}|com|org|net|gov|mil|biz|tel|info|mobi|name|aero|jobs|museum)$",$str);
	}
	
	protected function fail($message,$to=''){ // Hata bildirimi
		$_SESSION['message']=$message;
		@header('Location: '.($to!=''?$to:$_SERVER['HTTP_REFERER']));
		die();
	}
	
	protected function errors(){ // Hata göster
		$message=$_SESSION['message'];
		unset($_SESSION['message']);
		return $message;
	}
	
	function userlist(){
	$adjacents = 3;
	$query = "select id, usergroupid, firstname, lastname, email, password, gender, birthday, description, createdate, updatedate, isapproved, isdeleted, isbanned, issendmail, jobid from user where isdeleted = 0";
	//$total_pages = mysql_fetch_array(mysql_query($query));
	$total_pages = mysql_num_rows(mysql_query($query));
	
	$targetpage = "user.php";
	$limit = 5;
	$page = $_GET['page'];
	if($page) 
		$start = ($page - 1) * $limit;
	else
		$start = 0;
    $sql = "select id, usergroupid, firstname, lastname, email, password, gender, birthday, description, createdate, updatedate, isapproved, isdeleted, isbanned, issendmail, jobid from user where isdeleted = 0 LIMIT $start, $limit";
	$result = mysql_query($sql);
	
	echo "<div id=\"innerContent\">
    <div id=\"listHeader\">
      <p class=\"listInfos\">". $total_pages ." adet Kayit bulundu. </p>
    </div>
    <table cellspacing=\"0\" class=\"listTable\" id=\"postList\">
      <thead>
        <tr>
          <th class=\"first\"><div><a href=\"#\" title=\"id\">id</a><div></th>
          <th><a href=\"#\" title=\"usergroupid\">K.Grup Id</a></th>
          <th><a href=\"#\" title=\"firstname\">Adı</a></th>
          <th><a href=\"#\" title=\"lastname\">Soyadı</a></th>
          <th><a href=\"#\" title=\"email\">Email</a></th>
		  <th><a href=\"#\" title=\"gender\">Cinsiyet</a></th>
		  <th><a href=\"#\" title=\"isapproved\">Aktif</a></th>
		  <th><a href=\"#\" title=\"jobid\">Meslek</a></th>
		  <th class=\"last\"><a href=\"#\" title=\"actions\">Islemler</a></th>
        </tr>
      </thead>
	  <tfoot>
		  <tr>
		  <td colspan=\"9\">
              <div class=\"inner\">
                <div class=\"paginate\">";
	if ($page == 0) $page = 1;					
	$prev = $page - 1;							
	$next = $page + 1;							
	$lastpage = ceil($total_pages/$limit);		
	$lpm1 = $lastpage - 1;						
	
	$pagination = "";
	if($lastpage > 1)
	{	
		//previous button
		if ($page > 1) 
			echo  "<span class=\"prev\"><a href=\"$targetpage?page=$prev\">&lt;&lt; &#246;nceki</a></span>";
		else
			echo  "<span class=\"prev disabled\">&lt;&lt; &#246;nceki</span>";	
		
		//pages	
		if ($lastpage < 7 + ($adjacents * 2))	//not enough pages to bother breaking it up
		{	
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					echo  "<span class=\"current roundedBordersLite\">$counter</span>";
				else
					echo  "<span class=\"current roundedBordersLite\"><a href=\"$targetpage?page=$counter\">$counter</a></span>";					
			}
		}
		elseif($lastpage > 5 + ($adjacents * 2))	//enough pages to hide some
		{
			//close to beginning; only hide later pages
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						echo  "<span class=\"current roundedBordersLite\">$counter</span>";
					else
						echo  "<span class=\"current roundedBordersLite\"><a href=\"$targetpage?page=$counter\">$counter</a></span>";					
				}
				echo  "...";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=$lpm1\">$lpm1</a></span>";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=$lastpage\">$lastpage</a></span>";		
			}
			//in middle; hide some front and some back
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
				echo  "<span class=\"next\"><a href=\"$targetpage?page=1\">1</a></span>";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=2\">2</a></span>";
				echo  "...";
				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						echo  "<span class=\"current roundedBordersLite\">$counter</span>";
					else
						echo  "<span class=\"current roundedBordersLite\"><a href=\"$targetpage?page=$counter\">$counter</a></span>";					
				}
				echo  "...";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=$lpm1\">$lpm1</a></span>";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=$lastpage\">$lastpage</a></span>";		
			}
			//close to end; only hide early pages
			else
			{
				echo  "<span class=\"next\"><a href=\"$targetpage?page=1\">1</a></span>";
				echo  "<span class=\"next\"><a href=\"$targetpage?page=2\">2</a></span>";
				echo  "...";
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						echo  "<span class=\"current roundedBordersLite\">$counter</span>";
					else
						echo  "<span class=\"current roundedBordersLite\"><a href=\"$targetpage?page=$counter\">$counter</a></span>";					
				}
			}
		}
		
		//next button
		if ($page < $counter - 1) 
			echo  "<span class=\"next\"><a href=\"$targetpage?page=$next\">ileri »</a></span>";
		else
			echo  "<span class=\"next disabled\">ileri »</span>";
				
	}
	echo  "</div>
		      </div>
          </td>
        </tr>
      </tfoot>\n";
      echo "<tbody>";
        while($row = mysql_fetch_array($result))
		{
		   echo "<tr>";
		   echo "<td><div>".$row["id"]."</div></td>";
		   echo "<td><div>".$row["usergroupid"]."</div></td>";
		   echo "<td><div>".$row["firstname"]."</div></td>";
		   echo "<td><div>".$row["lastname"]."</div></td>";
		   echo "<td><div>".$row["email"]."</div></td>";
		   echo "<td><div>".$row["gender"]."</div></td>";
		   echo "<td><div>".$row["isapproved"]."</div></td>";
		   echo "<td><div>".$row["jobid"]."</div></td>";
		   echo "<td><div><a href=\"#\">Sil</a><a href=\"#\">D&uuml;zenle</a><a href=\"#\">Detaylar</a></div></td>";
		   echo "</tr>";
		}
		echo "</tbody>
    </table>
  </div>";
	}

}
$user = new user(); 
?>